package com.zsyc.model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.zsyc.util.DatabaseManager;

public class CodeQuestion {
    private static final Logger LOGGER = Logger.getLogger(CodeQuestion.class.getName());
    
    private Integer questionId;
    private String language;
    private String codeSnippet;
    private String correctAnswer;
    private String explanation;
    private String errorType;
    private String difficulty;
    private String category;
    private String createdAt;
    
    public CodeQuestion() {}
    
    public CodeQuestion(String language, String codeSnippet, String correctAnswer, 
                       String explanation, String errorType) {
        this.language = language;
        this.codeSnippet = codeSnippet;
        this.correctAnswer = correctAnswer;
        this.explanation = explanation;
        this.errorType = errorType;
        this.difficulty = "初级";
        this.category = "基础语法";
    }
    
    public CodeQuestion(String language, String codeSnippet, String correctAnswer, 
                       String explanation, String errorType, String difficulty, String category) {
        this.language = language;
        this.codeSnippet = codeSnippet;
        this.correctAnswer = correctAnswer;
        this.explanation = explanation;
        this.errorType = errorType;
        this.difficulty = difficulty;
        this.category = category;
    }
    
    public Integer getQuestionId() { return questionId; }
    public void setQuestionId(Integer questionId) { this.questionId = questionId; }
    
    public String getLanguage() { return language; }
    public void setLanguage(String language) { this.language = language; }
    
    public String getCodeSnippet() { return codeSnippet; }
    public void setCodeSnippet(String codeSnippet) { this.codeSnippet = codeSnippet; }
    
    public String getCorrectAnswer() { return correctAnswer; }
    public void setCorrectAnswer(String correctAnswer) { this.correctAnswer = correctAnswer; }
    
    public String getExplanation() { return explanation; }
    public void setExplanation(String explanation) { this.explanation = explanation; }
    
    public String getErrorType() { return errorType; }
    public void setErrorType(String errorType) { this.errorType = errorType; }
    
    public String getDifficulty() { return difficulty; }
    public void setDifficulty(String difficulty) { this.difficulty = difficulty; }
    
    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }
    
    public String getCreatedAt() { return createdAt; }
    public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
    
    public boolean save() {
        String sql = "INSERT INTO code_question (language, code_snippet, correct_answer, explanation, error_type, difficulty, category) VALUES (?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, language);
            pstmt.setString(2, codeSnippet);
            pstmt.setString(3, correctAnswer);
            pstmt.setString(4, explanation);
            pstmt.setString(5, errorType);
            pstmt.setString(6, difficulty);
            pstmt.setString(7, category);
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (Statement stmt = conn.createStatement();
                     ResultSet rs = stmt.executeQuery("SELECT last_insert_rowid()")) {
                    if (rs.next()) {
                        this.questionId = rs.getInt(1);
                    }
                }
                LOGGER.info("代码题目保存成功: " + language + " (ID: " + questionId + ")");
                return true;
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "保存代码题目失败: " + language, e);
        }
        return false;
    }
    
    public static List<CodeQuestion> getAllQuestions() {
        List<CodeQuestion> questions = new ArrayList<>();
        String sql = "SELECT * FROM code_question ORDER BY created_at DESC";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                CodeQuestion question = new CodeQuestion();
                question.setQuestionId(rs.getInt("question_id"));
                question.setLanguage(rs.getString("language"));
                question.setCodeSnippet(rs.getString("code_snippet"));
                question.setCorrectAnswer(rs.getString("correct_answer"));
                question.setExplanation(rs.getString("explanation"));
                question.setErrorType(rs.getString("error_type"));
                question.setDifficulty(rs.getString("difficulty"));
                question.setCategory(rs.getString("category"));
                question.setCreatedAt(rs.getString("created_at"));
                questions.add(question);
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取所有代码题目失败", e);
        }
        return questions;
    }
    
    public static List<CodeQuestion> getQuestionsByLanguage(String language) {
        List<CodeQuestion> questions = new ArrayList<>();
        String sql = "SELECT * FROM code_question WHERE language = ? ORDER BY created_at DESC";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, language);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    CodeQuestion question = new CodeQuestion();
                    question.setQuestionId(rs.getInt("question_id"));
                    question.setLanguage(rs.getString("language"));
                    question.setCodeSnippet(rs.getString("code_snippet"));
                    question.setCorrectAnswer(rs.getString("correct_answer"));
                    question.setExplanation(rs.getString("explanation"));
                    question.setErrorType(rs.getString("error_type"));
                    question.setDifficulty(rs.getString("difficulty"));
                    question.setCategory(rs.getString("category"));
                    question.setCreatedAt(rs.getString("created_at"));
                    questions.add(question);
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "根据语言获取代码题目失败", e);
        }
        return questions;
    }
    
    public static List<CodeQuestion> getQuestionsByDifficulty(String language, String difficulty) {
        List<CodeQuestion> questions = new ArrayList<>();
        String sql = "SELECT * FROM code_question WHERE language = ? AND difficulty = ? ORDER BY RANDOM()";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, language);
            pstmt.setString(2, difficulty);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    CodeQuestion question = new CodeQuestion();
                    question.setQuestionId(rs.getInt("question_id"));
                    question.setLanguage(rs.getString("language"));
                    question.setCodeSnippet(rs.getString("code_snippet"));
                    question.setCorrectAnswer(rs.getString("correct_answer"));
                    question.setExplanation(rs.getString("explanation"));
                    question.setErrorType(rs.getString("error_type"));
                    question.setDifficulty(rs.getString("difficulty"));
                    question.setCategory(rs.getString("category"));
                    question.setCreatedAt(rs.getString("created_at"));
                    questions.add(question);
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "根据难度获取代码题目失败", e);
        }
        return questions;
    }
    
    public static List<CodeQuestion> getRandomQuestions(String language, int count) {
        List<CodeQuestion> questions = new ArrayList<>();
        String sql = "SELECT * FROM code_question WHERE language = ? ORDER BY RANDOM() LIMIT ?";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, language);
            pstmt.setInt(2, count);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    CodeQuestion question = new CodeQuestion();
                    question.setQuestionId(rs.getInt("question_id"));
                    question.setLanguage(rs.getString("language"));
                    question.setCodeSnippet(rs.getString("code_snippet"));
                    question.setCorrectAnswer(rs.getString("correct_answer"));
                    question.setExplanation(rs.getString("explanation"));
                    question.setErrorType(rs.getString("error_type"));
                    question.setDifficulty(rs.getString("difficulty"));
                    question.setCategory(rs.getString("category"));
                    question.setCreatedAt(rs.getString("created_at"));
                    questions.add(question);
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取随机题目失败", e);
        }
        return questions;
    }
    
    public static List<String> getAllLanguages() {
        List<String> languages = new ArrayList<>();
        String sql = "SELECT DISTINCT language FROM code_question ORDER BY language";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                languages.add(rs.getString("language"));
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取语言列表失败", e);
        }
        return languages;
    }
    
    public static List<String> getAllDifficulties() {
        List<String> difficulties = new ArrayList<>();
        String sql = "SELECT DISTINCT difficulty FROM code_question ORDER BY difficulty";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                difficulties.add(rs.getString("difficulty"));
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取难度列表失败", e);
        }
        return difficulties;
    }
    
    public static boolean importQuestions(List<CodeQuestion> questions) {
        String sql = "INSERT OR IGNORE INTO code_question (language, code_snippet, correct_answer, explanation, error_type, difficulty, category) VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            conn.setAutoCommit(false);
            for (CodeQuestion question : questions) {
                pstmt.setString(1, question.getLanguage());
                pstmt.setString(2, question.getCodeSnippet());
                pstmt.setString(3, question.getCorrectAnswer());
                pstmt.setString(4, question.getExplanation());
                pstmt.setString(5, question.getErrorType());
                pstmt.setString(6, question.getDifficulty());
                pstmt.setString(7, question.getCategory());
                pstmt.addBatch();
            }
            
            int[] results = pstmt.executeBatch();
            conn.commit();
            conn.setAutoCommit(true);
            
            int successCount = 0;
            for (int result : results) {
                if (result >= 0) successCount++;
            }
            
            LOGGER.info("成功导入 " + successCount + " 道代码题目");
            return successCount > 0;
            
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "批量导入代码题目失败", e);
            return false;
        }
    }
}
